package com.ytjj.qmyx.supplychain.service;

import com.ytjj.qmyx.supplychain.common.api.ResultCode;
import com.ytjj.qmyx.supplychain.common.enums.AdminStatusEnums;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.mapper.AdminMapper;
import com.ytjj.qmyx.supplychain.mapper.BankerMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.YxAdmin;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBanker;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class AdminService {
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private BankerMapper bankerMapper;

    public YxAdmin queryByEmail(String email) {
        Example example = new Example(YxAdmin.class);
        example.createCriteria().andEqualTo("email", email)
                .andEqualTo("status", AdminStatusEnums.ACTIVATION.getStatus().byteValue());
        List<YxAdmin> admins = adminMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(admins)) {
            return null;
        }
        return admins.get(0);
    }

    public YxAdmin getCurAdmin() {
        YxAdmin admin  =  (YxAdmin)SecurityUtils.getSubject().getPrincipal();
        if(admin == null){
            throw new ApiException("获取账号失败！");
        }
        return admin;
    }
    /**
     * 获取当前用户的信息
     *
     * @return
     */
    public YxBanker getUserInfo() {
        String principal = getCurBankerTel();
        YxBanker yxBanker = queryBankerByTel(principal);
        return yxBanker;
    }

    public String getCurBankerTel() {
        String tel = (String) SecurityUtils.getSubject().getPrincipal();
        if (null == tel) {
            throw new ApiException(ResultCode.UNAUTHORIZED);
        }
        return tel;
    }

    public YxBanker queryBankerByTel(String tel) {
        Example example = new Example(YxBanker.class);
        example.createCriteria().andEqualTo("tel", tel);
        List<YxBanker> list = bankerMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    public static String getCurAdminEmail(){
        YxAdmin admin  =  (YxAdmin)SecurityUtils.getSubject().getPrincipal();
        if(admin == null){
            throw new ApiException("获取账号失败！");
        }
        return admin.getEmail();
    }

}
